// pages/present/present.js
import wxValidate from '../../utils/wxValidate.js'
const host = require('../../config.js').host;
const network = require('../../utils/network.js');
const graceChecker = require('../../utils/graceChecker.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: '',
    host: host,
    formData: {},
    storePhotoList: [],
    goods: {
      name: "经典双喜香烟",
      price: '12',
      expiryDate: '2020-12-13',
      totalStock: '999',
      goodsImage: '',
      goodsOwnerId: '0',
    },
    ownerList: [{
        "ownerId": -1,
        "ownerName": 'woshi yezhu1'
      },
      {
        "ownerId": -2,
        "ownerName": 'woshi 业主2'
      },

    ],
    ownerIndex: -1,
    checkOwnerId: 0, // 选中的业主
    userType: '-1', //用户类型
  },
  // 获取合作的业主
  getOwnerList() {

    network.requestGet("/xcx/customer-relation/merchant-owner-list", {
      'isBinding': '1',
      'relationType': '0',

    }, res => {
      this.setData({
        ownerList: res.data.data,
      });
      console.log("ownerList", this.data.ownerList); 
      //this.data.ownerList = res.data.data;
    });

  },
  // 获取选中的业主
  bindPickerChange1(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    // goods_owner_id
    let checkedOwner = this.data.ownerList[e.detail.value];
    if ("undefined" != typeof (checkedOwner)) {
      this.setData({
        ownerIndex: e.detail.value,
        checkOwnerId: checkedOwner.ownerId,
        'goods.goodsOwnerId': checkedOwner.ownerId,
      })
    }

  },
  //判断字符是否为空
  isEmpty(obj) {
    return (typeof obj === 'undefined' || obj === null || obj === "");
  },
  // 

  // 添加 商品提交
  formSubmit: function (e) {
    this.data.goods.name = e.detail.value.name;
    this.data.goods.price = e.detail.value.price;
    this.data.goods.expiryDate = this.data.date;
    this.data.goods.totalStock = e.detail.value.totalStock;
    this.data.goods.costPrice = e.detail.value.costPrice;
    //this.data.goods.goodsImage = e.detail.value.goodsImage;
    // 校验参数
    let goods = this.data.goods;
    const params = e.detail.value
    var rule = [ // 表单的字段 校验
      {
        name: "name",
        checkType: "notnull",
        checkRule: "",
        errorMsg: "请输入商品名称"
      },
      {
        name: "price",
        checkType: "xiaoshu2",
        checkRule: "",
        errorMsg: "请输入正确的商品价格"
      },
      {
        name: "costPrice",
        checkType: "xiaoshu2",
        checkRule: "",
        errorMsg: "请输入正确的商品成本价"
      },
      {
        name: "totalStock",
        checkType: "notnull",
        checkRule: "",
        errorMsg: "请输入总库存数量"
      },
      {
        name: "expiryDate",
        checkType: "notnull",
        checkRule: "",
        errorMsg: "请输入活动有效期"
      },
      //{name:"goodsImage", checkType : "notnull", checkRule:"",  errorMsg:"请添加商品图片"},
    ];
    //校验表单
    var checkRes = graceChecker.check(params, rule);
    if (!checkRes) {
      wx.showToast({
        title: graceChecker.error,
        icon: "none"
      });
      return;
    }
    // 判断用户 类型
    if(1 == this.data.userType){ // 如果是商家添加商品 需要有合作的业主
      let goodsOwnerId = this.data.goods.goodsOwnerId;
      if(0 == goodsOwnerId){
        wx.showToast({
          title: '请选择合作的业主,再添加物品',
          icon: "none"
        });
        return;
      }

    }
    // 业主添加商品
    if (0 == this.data.userType) {// 如果是业主添加商品 需要有合作的商家--从全局获取
      this.data.goods.goodsMerchantId = getApp().globalData.ownerCarryMerchantId;
    }
    if(!this.data.goods.goodsImage){
      wx.showToast({
        title: '请选择添加图片',
        icon: "none"
      });
      return;
    }



    network.requestPost("/xcx/goods/add", goods, res => {
      let resData = res.data;
      setTimeout(function () {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }, 800)
    });
    //end
  },

  // 选中日期
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  //选中图片
  chooseStorePhotos() {
    let that = this;
    let formData = this.data.formData;
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      success: function (res) {
        network.uploadFileLoading("/common/upload", res.tempFiles[0].path, res => {
          let data = JSON.parse(res.data);
          let servicePath = data.fileName;
          let imgUrl = host + servicePath;
          that.data.goods.goodsImage = servicePath;
          that.setData({
            formData: formData,
            storePhotoList: [imgUrl]
          })
        })
      }
    });
  },
  // 图片回显?
  viewStorePhoto(e) {
    wx.previewImage({
      urls: this.data.storePhotoList,
      current: e.currentTarget.dataset.url
    });
  },

  /**
   * 删除图片
   */
  DelImg(e) {
    let type = e.currentTarget.dataset.type;
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          if (type == 1) {
            let imgList = this.data.storePhotoList;
            imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
              storePhotoList: imgList
            })
          }
          if (type == 2) {
            let imgList = this.data.tradingCertificateList;
            imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
              tradingCertificateList: imgList
            })
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOwnerList();
    this.setData({
      userType: getApp().globalData.userType,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})